<template>
  <div>
    <TopFilter :list="topFilterList" :cols="4" :labelWidth="95" :rows="1" :collapse="false" @filterChange="changeHandle" @onCollapse="collapseHandle" />
    <FilterTable
      ref="table"
      columnsRef="partPartPurchasePurchasePlaneIndex"
      :columns="columns"
      :fetchapi="fetchapi"
      :params="fetchParams"
      :datakey="'rows'"
      :onRowSelectChange="selectChangeHandler"
      :onColumnsChange="columns => (this.columns = columns)"
    >
      <template slot="moreActions">
        <span @click="removeHandler">删除明细</span>
      </template>
      <template slot="controls">
        <el-button size="small" type="primary" icon="el-icon-plus" @click="addRecordHandler">新建</el-button>
        <!-- <el-button size="small" icon="iconfont icon-yulan">预览</el-button> -->
        <!-- <el-button size="small" icon="iconfont icon-daochu">导出</el-button> -->
        <!-- <el-button size="small" icon="iconfont icon-dayin">打印</el-button> -->
      </template>
    </FilterTable>
    <!-- 配件详情 -->
    <BaseDialog :visible.sync="detailVisible" title="配件详细" destroyOnClose>
      <detailModal :billNo="viewBillNo" />
    </BaseDialog>
    <!-- 供应商选择 -->
    <BaseDialog :visible.sync="shelperVisible" title="供应商查询" destroyOnClose :containerStyle="{ height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px' }">
      <provideSearchHelper @close="shelperVisible = false" @onConfirm="handleDealerConfirm" />
    </BaseDialog>
    <!-- 添加一级抽屉 -->
    <Drawer :visible.sync="actionPanel.visible" :title="actionPanel.title" destroyOnClose :containerStyle="{ height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px' }">
      <actionPanel :isAdd="isAdd" :billId="editBillId" @close="closeActionPanel" @reSearchTableData="handleResearchTableData" />
    </Drawer>
  </div>
</template>

<script>
import { queryPurchasePlanList, getAllUser, deletePartPurhcasePlan } from '@/api/part/partPurchase/purchasePlane';

import { dictionary } from '@/utils/dictMixin';
import { authority } from '@/utils/authMixin';
import { confirmAction, notifyAction } from '@/utils';

import detailModal from './detailModal';
import provideSearchHelper from './provideSearchHelper';
import actionPanel from './actionPanel';

export default {
  name: 'ProcurementPlan',
  components: {
    detailModal,
    provideSearchHelper,
    actionPanel
  },
  mixins: [dictionary, authority],
  data() {
    this.selectedRows = [];
    return {
      topFilterList: this.createTopFilters(),
      columns: this.createTableColumns(),
      list: [],
      fetchapi: queryPurchasePlanList,
      fetchParams: { xhrAbort: false },
      detailVisible: false,
      shelperVisible: false,
      selectPartDialogVisible: false,
      batchSelectPartDialogVisible: false,
      actionPanel: {
        type: 'add',
        title: '',
        visible: false
      },
      isAdd: true, // 是否是添加模式
      detailData: {}, // 详情数据
      editBillId: 0, // 编辑的单据编号
      viewBillNo: '', // 查看详情的订单编号
      selectedDealerInfo: {}, // 选中的经销商信息
      salerData: {} // 销售数据（翻译用）
    };
  },
  mounted() {
    this.getUserList();
    this.BaseTable = this.$refs.table.$refs.pageTable;
  },
  methods: {
    createTopFilters() {
      return [
        // {
        //   type: 'SELECT',
        //   label: '网络',
        //   fieldName: 'a1',
        //   placeholder: '请选择...',
        //   itemList: [{ text: '00', value: '1' }, { text: '11', value: '2' }],
        //   rules: [{ required: true, message: '请选择网络', trigger: 'change' }]
        // },
        {
          type: 'INPUT',
          label: '采购计划编号',
          fieldName: 'vBillNo',
          placeholder: '请输入...'
        },
        {
          type: 'INPUT',
          label: '供应商',
          fieldName: 'vSupplierid',
          placeholder: '请选择...',
          unitRender: () => {
            return <el-button slot="append" icon="el-icon-search" onClick={this.searchHelper}></el-button>;
          },
          readonly: true
          // rules: [{ required: true, message: '请选择供应商', trigger: 'blur' }]
        },
        {
          type: 'RANGE_DATE',
          label: '计划日期',
          style: { minWidth: '200px' },
          dateFormat: 'yyyy-MM-dd',
          fieldName: 'startDForecast|endDForecast'
        }
      ];
    },
    createTableColumns() {
      return [
        {
          title: '操作',
          dataIndex: 'column-action',
          width: 100,
          fixed: 'left',
          render: (props, h) => {
            return (
              <div>
                <el-button size="mini" type="text" onClick={() => this.detailsHandler(props.row)}>
                  详情
                </el-button>
                <el-divider direction="vertical" />
                <el-button size="mini" type="text" onClick={() => this.editRecordHandler(props.row)}>
                  编辑
                </el-button>
              </div>
            );
          }
        },
        {
          title: '序号',
          dataIndex: 'index',
          width: 70,
          sorter: true,
          render: props => {
            return <span>{props.row.index + 1}</span>;
          }
        },
        // {
        //   title: '网络',
        //   dataIndex: 'a1',
        //   sorter: true,
        //   filter: true,
        //   filterType: 'input'
        // },
        {
          title: '采购计划编号',
          dataIndex: 'vBillNo',
          sorter: true,
          filter: true,
          filterType: 'input'
        },
        {
          title: '单据状态',
          dataIndex: 'vStatus',
          sorter: true,
          filter: true,
          filterType: 'checkbox',
          filterItems: this.createDictList('8133'),
          render: params => {
            return <span>{this.createDictText(params.row.vStatus, '8133')}</span>;
          }
        },
        {
          title: '供应商代码',
          dataIndex: 'nSupplierid',
          sorter: true,
          filter: true,
          filterType: 'input'
        },
        {
          title: '供应商名称',
          dataIndex: 'customerName',
          sorter: true,
          filter: true,
          filterType: 'input',
          showOverflowTooltip: true
        },
        {
          title: '计划日期',
          dataIndex: 'dForecast',
          dateFormat: 'yyyy-MM-dd',
          sorter: true,
          filter: true,
          filterType: 'date-range',
          dateFormat: 'yyyy-MM-dd'
        },
        {
          title: '操作员',
          dataIndex: 'updatedBy',
          sorter: true,
          filter: true,
          filterType: 'input',
          render: params => {
            return <span>{this.salerData[params.row.updatedBy]}</span>;
          }
        }
      ];
    },
    selectChangeHandler(rows) {
      this.selectedRows = rows;
    },
    searchHelper() {
      this.shelperVisible = true;
    },
    // 插叙所有员工
    async getUserList() {
      let res = await getAllUser();
      if (res.resultCode == 200) {
        let obj = {};
        res.data.map(item => {
          obj[item.userId] = item.employeeName;
        });
        this.salerData = obj;
      }
    },
    // 点击搜索或者重置
    changeHandle(val) {
      this.fetchParams.xhrAbort = true;
      this.fetchParams = Object.assign(this.fetchParams, {
        xhrAbort: false,
        ...val,
        vSupplierid: val.vSupplierid ? this.selectedDealerInfo.customerCode : '',
        endDForecast: val.endDForecast ? val.endDForecast.split(' ')[0] : '',
        startDForecast: val.startDForecast ? val.startDForecast.split(' ')[0] : ''
      });
    },
    // 供应商选择点击确定
    handleDealerConfirm(e) {
      this.selectedDealerInfo = e;
      this.topFilterList.find(item => item.fieldName == 'vSupplierid').initialValue = e.customerName;
    },
    // 点击添加
    addRecordHandler() {
      this.isAdd = true;
      this.actionPanel = { type: 'add', title: '新建配件采购计划', visible: true };
    },
    // 点击编辑
    editRecordHandler(e) {
      this.isAdd = false;
      this.editBillId = e.itemId;
      this.actionPanel = { type: 'add', title: '编辑采购计划', visible: true };
    },
    async removeHandler() {
      if (this.selectedRows.length) {
        let itemIdList = this.selectedRows.map(item => item.itemId);
        confirmAction('此操作将删除该采购计划，是否继续？')
          .then(async confirm => {
            let res = await deletePartPurhcasePlan({
              items: itemIdList.join(',')
            });
            if (res.resultCode == 200) {
              notifyAction('删除成功', 'success');
              this.fetchParams.xhrAbort = true;
              this.fetchParams.xhrAbort = false;
            }
          })
          .catch(err => {
            console.log(err, '删除点击取消');
          });
      } else {
        notifyAction('请先选择需要删除的采购计划', 'warning');
      }
    },
    detailsHandler(row) {
      this.viewBillNo = row.vBillNo;
      this.detailVisible = true;
    },
    closeProvideSearchHelper(val) {},
    closeActionPanel(val) {
      this.actionPanel.visible = val;
    },
    collapseHandle() {
      this.$nextTick(() => {
        this.BaseTable.EXECUTE_RESET_HEIGHT();
      });
    },
    // 重新查询table数据
    handleResearchTableData() {
      this.fetchParams.xhrAbort = true;
      this.fetchParams.xhrAbort = false;
    }
  }
};
</script>

<style lang="less" scoped></style>
